const ajax = (options) => {
  //设置默认的options
  let defaults = {
    type: 'Get',
    url: '',
    data: {},
    header: {'Content-Type': 'application/x-www-form-urlencoded'},
    success: () => {},
    error: () => {}
  }
  Object.assign(defaults, options)
  //type不一样，传参形式也不一样
  let params = ''
  for (let param in defaults.data) {
    params += param + '=' + defaults.data[param] + '&'
  }
  params = params.substr(0, params.length - 1)
  if (defaults.type === 'GET') {
    defaults.url = defaults.url + '?' + params
  }
  const request = new XMLHttpRequest()
  request.open(defaults.type, defaults.url)
  request.onreadystatechange = () => {
    if (request.readyState === 4) {
      if (request.status >= 200 && request.status < 300) {
        defaults.success(request.responseText)
      } else {
        defaults.error(request.responseText)
      }
    }
  }
  if (defaults.type === 'Post') {
    const contentType = defaults.header['Content-Type']
    request.setRequestHeader('Content-Type', contentType)
    if (contentType === 'application/x-www-form-urlencoded') {request.send(params)} else if (contentType === 'application/json') {
      request.send(JSON.stringify(defaults.data))
    }
  }else {
    request.send()
  }
}